<template>
	<div class="layout">
		<div id="title">找回密码</div>
		<div id="stepOne" v-show="step == 1">
			<StepBar :step="1" :flag="true"></StepBar>
			<div class="formDiv">
        <el-form ref="form1" :model="register" :rules="registerRules1" label-width="110px">
					<el-form-item label="用户名：" prop="userName">
						<el-input v-model.trim="register.userName" placeholder="请输入用户名" maxLength="20" @input="register.userName = register.userName.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, '')"></el-input>
					</el-form-item>
					<el-form-item label="手机号码：" prop="userPhone">
						<el-input v-model.trim="register.userPhone" placeholder="请输入手机号码" :maxlength="11" @input="register.userPhone = register.userPhone.replace(/[^\d]/g,'')"></el-input>
					</el-form-item>
					<el-form-item label="手机验证码：" prop="authCode">
						<div id="codeDiv">
							<el-input v-model.trim="register.authCode" placeholder="请输入验证码" maxLength="6"></el-input>
							<div class="sendCodeBtn" @click="sendAuthCode" v-if="textCount < 0">获取短信验证码</div>
							<div class="cantSendBtn" v-if="textCount >= 0">{{'已发送(' + (textCount < 10 ? ('0' + textCount) : textCount) + '秒)'}}</div>
						</div>
					</el-form-item>
					<el-form-item label="图形验证：" prop="imgCode">
						<div id="codeDiv">
							<el-input v-model.trim="register.imgCode" class="loginInput" placeholder="图形验证码" maxLength="2"></el-input>
							<img class="captchaImg" :src="captchaImage" @click="getCaptchaImage">
						</div>
					</el-form-item>
				</el-form>
				<!-- <div class="btnDiv"> -->
          <Buttons :buttons="buttons_stepOne" @infoAuth="infoAuth"></Buttons>
					<!-- <div class="btn" style="background-color: #045db9; color: #f1f2f4" @click="infoAuth">下一步</div> -->
				<!-- </div> -->
			</div>
		</div>
		<div id="stepTwo" v-show="step == 2">
			<StepBar :step="2" :flag="true"></StepBar>
			<div class="formDiv">
				<el-form ref="form2" :model="register" :rules="registerRules2" label-width="110px">
					<el-form-item label="用户密码：" prop="password">
						<el-input type="password" v-model.trim="register.password" :type="pwInputtype" placeholder="请输入新密码" maxLength="18">
							<i slot="suffix" class="el-input__icon el-icon-view" @click="pwInputtype = (pwInputtype == 'password' ? 'text' : 'password')"></i>
						</el-input>
					</el-form-item>
					<el-form-item label="重复密码：" prop="repeatPassword">
						<el-input type="password" v-model.trim="register.repeatPassword" :type="repwInputtype" placeholder="请确认新密码" maxLength="18">
							<i slot="suffix" class="el-input__icon el-icon-view" @click="repwInputtype = (repwInputtype == 'password' ? 'text' : 'password')"></i>
						</el-input>
					</el-form-item>
				</el-form>
				<div class="btnDiv" style="margin-bottom: 200px">
          <Buttons :buttons="buttons_stepTwo" @createUser="createUser" @back="step--"></Buttons>
					<!-- <div class="btn" @click="step--">上一步</div>
					<div class="btn" style="background-color: #045db9; color: #f1f2f4" @click="createUser">确认修改</div> -->
				</div>
			</div>
		</div>
		<div id="stepThree" v-show="step == 3">
			<StepBar :step="3" :flag="true"></StepBar>
			<div class="doneDiv">
				<div class="successTitle">
					<img src="@/assets/image/register/checkIcon.png"></img>
					<span style="margin-left: 10px">密码修改成功！</span>
				</div>
				<div style="margin: 20px; font-size: 15px">账户密码已修改成功，现在您可以使用新密码进行登录。</div>
				<!-- 立即登录 -->
          <Buttons :buttons="buttons_stepThree" @toLogin="toLogin"></Buttons>
				<!-- <div class="loginBtn" @click="toLogin()">返回登录页登录</div>  -->
			</div>
		</div>
	</div>
</template>

<script>
	import StepBar from './components/stepBar'

	import {isPhone, isEmptyStr} from "@/utils/util";

  import forgot from '@/formRules/userAccount/forgot.js';
  import { getCaptchaImage, getAuthCode } from "@/common/api.js";
  import { getInfoAuth, createUser, checkUserName } from "@/common/api/logOrReg.js";

	export default {
		name: "",
		components: { StepBar},
    mixins: [forgot],
		data() {
			return {
        buttons_stepOne:[{text:"下一步",type:"success",size:"l",method:"infoAuth"}],
        buttons_stepTwo:[
          {text:"上一步",type:"normal",size:"l",method:"back"},
          {text:"确认修改",type:"success",size:"l",method:"createUser"},
        ],
        buttons_stepThree:[{text:"返回登录页登录",type:"success",size:"xxl",method:"toLogin"}],
				step: 1,
				legalRepresentativeTypes: [],
				legalpersonTypes: [],
				applyTypes: [],
				pwInputtype: 'password',
				repwInputtype: 'password',
				textCount: -1, //短信倒计时
				captchaImage: '', // 图形验证码
				userId: '' // 用户id
			}
		},
		methods: {
			/**
			 * 返回上一页
			 */
			backPage: function () {
				window.history.go(-1)
			},
			/**
			 * 跳转登录页
			 */
			toLogin: function () {
				let ns = this
				ns.$router.push({path: 'login'})
			},
			/**
			 * 获取验证码图片
			 */
    async getCaptchaImage() {
      let res = await getCaptchaImage()
      console.log("res",res)
      this.captchaImage = "data:image/gif;base64," + res.img;
      this.register.uuid = res.uuid;
    },
			/**
			 * 认证企业信息
			 */
			async infoAuth () {
        let ok = false
				this.$refs['form1'].validate(async valid => {
          if(valid) ok = true;
        })
        if(!ok) return ;
        let arrParams = {
          userName: this.register.userName,
          userPhone: this.register.userPhone,
          authCode: this.register.authCode,
          authType: 'update_pwd',
          imgCode: this.register.imgCode,
          uuid: this.register.uuid
        }
        let res = await getInfoAuth(arrParams);
        if (res.code == 200) {
          this.userId = res.data
          this.step++
        } else {
          this.$message.error(res.msg);
          this.getCaptchaImage()
        }
			},
			/**
			 * 检查注册用户填写是否规范
			 * @return 是否规范提示，规范则返回空字符串
			 */
			/**
			 * 注册用户
			 */
			async createUser() {
        let ok = false
				this.$refs['form2'].validate(valid => {
          if(valid) ok = true;
        })
        if(!ok) return ;
        
        let arrParams = {
          userId: this.userId,
          password: this.register.password,
          userPhone: this.register.userPhone,
          authCode: this.register.authCode
        }
        let res = await createUser(arrParams);
        console.log("res",res)
        if (res.code == 200) {
          this.step++
        } else {
        this.$message.error(res.msg);
        }
			},
			/**
			 * 发送短信验证码
			 */
			async sendAuthCode() {
        let ok = false
				this.$refs['form1'].validateField('userPhone', (valid) => {
          if(!valid) ok = true;
        })
        if(!ok) return ;
        let obj = {
          userName: this.register.userName,
          userPhone: this.register.userPhone
        }
        let data = {
          userPhone: this.register.userPhone,
          authType: 'update_pwd'
        }
        let res = await checkUserName(obj);
        if(res.code == 200) {
          // 校验成功之后，在请求放短信接口
          let result = await getAuthCode(data);
            if(result.code == 200) {
              this.textCount = 120
              var timer = setInterval(counting, 1000);
              function counting() {
                this.textCount--
                if (this.textCount < 0) {
                  clearInterval(timer)
                }
              }
            } else {
              this.$message.error(result.msg)
            }
          
        } else {
          this.$message.error(res.msg)
        }
			}
		},
		mounted() {
			this.getCaptchaImage()
		}
	}
</script>

<style scoped>
	#title {
		width: 800px;
		text-align: left;
		margin: 0 auto;
		margin-top: 30px;
		color: #045db9;
		font-size: 20px;
		font-weight: bold;
	}

	.formDiv {
		margin: 0 auto;
		width: 800px;
		text-align: left;
	}

	.formDiv .agreementDiv:hover {
		cursor: pointer;
		text-decoration: underline;
	}

	.formDiv .btnDiv {
		display: flex;
		justify-content: center;
		padding-left: 170px;
		margin-bottom: 100px;
	}

	.formDiv .btnDiv .btn {
		padding: 10px 10px;
		background-color: #f1f2f4;
		color: #045db9;
		margin-right: 20px;
		width: 100px;
		text-align: center;
		font-size: 15px;
		border-radius: 5px;
	}

	.formDiv .btnDiv .btn:hover {
		cursor: pointer;
		box-shadow: 0px 0px 5px #888888;
		transition: all 0.2s ease 0s;
	}

	.formDiv #codeDiv {
		display: flex
	}

	::v-deep .formDiv #codeDiv .el-input .el-input__inner {
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
	}

	.formDiv #codeDiv .sendCodeBtn {
		white-space: nowrap;
		background-color: #f1f2f4;
		color: #045db9;
		width: 140px;
		text-align: center;
		border-top-right-radius: 4px;
		border-bottom-right-radius: 4px;
	}

	.formDiv #codeDiv .sendCodeBtn:hover {
		cursor: pointer;
		box-shadow: 0px 0px 3px #888888;
		transition: all 0.2s ease 0s;
	}

	.formDiv #codeDiv .cantSendBtn {
		white-space: nowrap;
		background-color: #f1f2f4;
		color: #045db9;
		width: 120px;
		text-align: center;
		border-top-right-radius: 4px;
		border-bottom-right-radius: 4px;
	}

	.formDiv #codeDiv .cantSendBtn:hover {
		cursor: pointer;
	}

	.doneDiv {
		margin-top: 100px;
		margin-bottom: 200px;
	}

	.doneDiv .successTitle {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		font-size: 25px;
	}

	.doneDiv .loginBtn {
		background-color: #045db9;
		color: #f1f2f4;
		padding: 10px 10px;
		width: 130px;
		margin: 0 auto;
		border-radius: 5px;
		margin-top: 50px;
	}

	.doneDiv .loginBtn:hover {
		cursor: pointer;
		box-shadow: 0px 0px 5px #888888;
		transition: all 0.2s ease 0s;
	}

	.layout {
		min-height: 100vh;
		position: relative;
		padding-bottom: 150px;
		box-sizing: border-box;
	}

	.footer {
		position: absolute;
		bottom: 0;
		width: 100%;
	}
	.captchaImg{
		height: 40px;
		width: 140px;
		cursor: pointer;
	}
</style>
